package com.woniu.zhoukao.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.zhoukao.entity.User;
import com.woniu.zhoukao.service.OrderService;
import com.woniu.zhoukao.service.UserService;
import com.woniu.zhoukao.utils.CookieUtils;
import com.woniu.zhoukao.utils.JwtUtils;
import com.woniu.zhoukao.vo.MyOrderVO;
import com.woniu.zhoukao.vo.OrderPreviewVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuao
 * @since 2023-02-07 09:47:30
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;


    @RequestMapping("allItems")
    public OrderPreviewVo allItems(@RequestParam("productIds[]") Integer[] productIds, HttpServletRequest request){

        User currentUser = getCurrentUser(request);
        OrderPreviewVo orderPreviewVo = orderService.queryOrderPreview(currentUser.getId(), productIds);

        return orderPreviewVo;
    }


    private User getCurrentUser(HttpServletRequest request){
        //获取已登录用户信息
        // 1.先从request拿到token
        // 2.从token获取到用户名
        // 3.根据用户名查询到用户信息
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);

        return userService.getUserByUserName(account);
    }

    @PostMapping("createOrder")
    public String createOrder(@RequestParam("productIds[]") Integer[] productIds, Integer addressId, HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        orderService.createOrder(currentUser.getId(),productIds,addressId);

        return "ok";
    }


    @PostMapping("pageQuery")
    public Page<MyOrderVO> pageQuery(Integer currentPage, Integer pageSize, HttpServletRequest request){

        User currentUser = getCurrentUser(request);

        Page<MyOrderVO> pageData = orderService.pageQuery(currentUser.getId(), currentPage, pageSize);

        return pageData;
    }

}

